package com.interview.server.utils;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FilenameUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;

/**
 * 文件上传工具类
 *
 * @author shaobin
 * @date 2021-03-29
 */

public class FileUploadUtils {

    private static final String FILE_UPLOAD_PATH = "D:\\upload";
    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws IOException IO异常
     */
    public static com.interview.server.domain.File upload(MultipartFile file) throws IOException{
        try
        {
            return upload(FILE_UPLOAD_PATH, file);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 文件上传
     *
     */
    public static com.interview.server.domain.File upload(String baseDir, MultipartFile file) throws IOException{
        UUID uuid = UUID.randomUUID();
        String fileName = extractFilename(file,uuid);
        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);
        String pathFileName = baseDir+ "/"+ fileName;
        com.interview.server.domain.File val = new com.interview.server.domain.File();
        val.setFilePath(pathFileName);
        val.setFileOriginalName(file.getOriginalFilename());
        val.setFileType(getExtension(file));
        val.setFileUuid(uuid.toString());
        val.setFileSize(file.getSize());
        return val;
    }

    /**
     * 编码文件名
     */
    public static String extractFilename(MultipartFile file, UUID uuid){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        fileName = simpleDateFormat.format(Calendar.getInstance().getTime()) + "/" + uuid;
        if(extension != null && !"".equals(extension)){
            fileName += "." + extension;
        }
        return fileName;
    }

    private static File getAbsoluteFile(String uploadDir, String fileName) {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }


    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static String getExtension(MultipartFile file){
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension))
        {
            extension = "";
        }
        return extension;
    }

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os 输出流
     * @throws IOException 文件瞎猜异常
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException{
        FileInputStream fis = null;
        try{
            File file = new File(filePath);
            if (!file.exists()){
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0){
                os.write(b, 0, length);
            }
        }
        catch (IOException e){
            throw e;
        }
        finally{
            if (os != null){
                try{
                    os.close();
                }
                catch (IOException e1){
                    e1.printStackTrace();
                }
            }
            if (fis != null){
                try{
                    fis.close();
                }
                catch (IOException e1){
                    e1.printStackTrace();
                }
            }
        }
    }

}
